package top.yuechenc.manage.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.yuechenc.manage.common.token.ShopResult;
import top.yuechenc.manage.common.token.UserLoginToken;
import top.yuechenc.manage.entity.SpCategory;
import top.yuechenc.manage.entity.SpCategoryDto;
import top.yuechenc.manage.service.CategoryService;

import java.util.List;
import java.util.UUID;

/**
 * 商品分类管理接口
 *
 * @author Zhiwei Wang
 * @date 2020/3/12 15:58
 */
@Api(description = "商品分类管理接口")
@RestController
@RequestMapping(value = "/api/cate")
public class CategoryController {
    private static final Logger log = LoggerFactory.getLogger(CategoryController.class);

    @Autowired
    private CategoryService categoryService;

    /**
     * 条件分页获取管理员列表
     */
    @ApiOperation(value = "条件分页获取商品类型列表")
    @UserLoginToken
    @PostMapping("/getByParam")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "query", defaultValue = "10")
    })
    private ShopResult getByParam(@RequestBody @ApiParam(name = "类型对象", value = "传入json格式") SpCategory spCategory, int pageNum, int pageSize) {
        ShopResult result;
        PageInfo<SpCategoryDto> spCategoryDtoPageInfo = null;
        try {
            spCategoryDtoPageInfo = categoryService.getByCatPid("0", pageNum, pageSize);
            if (spCategory.getCatLevel() == null) {
                spCategory.setCatLevel(2);
            }
            List<SpCategoryDto> dtoList = spCategoryDtoPageInfo.getList();
            for (SpCategoryDto spCategoryDto : dtoList) {
                if (spCategoryDto.getCatLevel() < spCategory.getCatLevel()) {
                    spCategoryDto.setChildren(findChildren(spCategoryDto.getCatId(), spCategory.getCatLevel()));
                }
            }
            spCategoryDtoPageInfo.setList(dtoList);
            log.info("分页获取商品分类列表，categoryPageInfo={}", spCategoryDtoPageInfo);
            result = new ShopResult(ShopResult.Metaa.SELECT, spCategoryDtoPageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(e.toString());
            result = new ShopResult(ShopResult.Metaa.SELECT_FAIL, e);
        }

        return result;
    }

    @ApiOperation(value = "添加分类")
    @UserLoginToken
    @PostMapping("/addCate")
    private ShopResult addCate(@RequestBody @ApiParam(name = "分类对象", value = "传入Json对象", required = true) SpCategory spCategory) {
        ShopResult result;
        if (spCategory != null) {
            spCategory.setCatId(UUID.randomUUID().toString());
            try {
                categoryService.addCate(spCategory);
                log.info("添加分类，spCategory={}", spCategory);
                result = new ShopResult(ShopResult.Metaa.OK, spCategory);
            } catch (Exception e) {
                e.printStackTrace();
                log.debug(e.toString());
                result = new ShopResult(ShopResult.Metaa.CREATED_FAIL, e.getMessage());
            }
        } else {
            result = new ShopResult(ShopResult.Metaa.CREATED_FAIL, "分类信息不能为空！");
        }
        return result;
    }

    @ApiOperation(value = "根据Id查询分类")
    @UserLoginToken
    @GetMapping(value = "/getById")
    @ApiImplicitParam(name = "catId", value = "分类编号", dataType = "string", paramType = "query")
    private ShopResult getById(String catId) {
        ShopResult result;
        if (catId != null && !"".equals(catId)) {
            SpCategory spCategory = categoryService.findById(catId);
            if (spCategory != null) {
                log.info("根据Id查询分类，spCategory={}", spCategory);
                result = new ShopResult(ShopResult.Metaa.SELECT, spCategory);
            } else {
                result = new ShopResult(ShopResult.Metaa.SELECT, "未查到该编号对应的分类信息");
            }
        } else {
            result = new ShopResult(ShopResult.Metaa.SELECT_FAIL, "请输入分类编号！");
        }
        return result;
    }

    @ApiOperation(value = "修改分类")
    @UserLoginToken
    @PostMapping(value = "/updCate")
    private ShopResult updCate(@RequestBody @ApiParam(name = "分类对象", value = "传入Json对象", required = true) SpCategory spCategory) {
        ShopResult res;
        if (spCategory.getCatId() != null && !"".equals(spCategory.getCatId())) {
            try {
                categoryService.updById(spCategory);
                spCategory = categoryService.findById(spCategory.getCatId());
                log.info("修改分类，spCategory={}", spCategory);
                res = new ShopResult(ShopResult.Metaa.UPDATE, spCategory);
            } catch (Exception e) {
                res = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, e.getMessage());
                log.debug(e.toString());
            }
        } else {
            res = new ShopResult(ShopResult.Metaa.UPDATE_FAIL, "请输入分类编号！");
        }
        return res;
    }

    @ApiOperation(value = "根据id删除分类信息")
    @UserLoginToken
    @GetMapping("/delCate")
    @ApiImplicitParam(name = "catId", value = "分类编号", dataType = "string", paramType = "query", required = true)
    private ShopResult delById(String catId) {
        ShopResult res;
        if (catId != null && !"".equals(catId)) {
            try {
                categoryService.delById(catId);
                log.info("修改分类，catId={}", catId);
                res = new ShopResult(ShopResult.Metaa.DELETED);
            } catch (Exception e) {
                res = new ShopResult(ShopResult.Metaa.DELETED_FAIL, e.getMessage());
                log.debug(e.toString());
            }
        } else {
            res = new ShopResult(ShopResult.Metaa.DELETED_FAIL, "：请输入分类编号！");
        }
        return res;
    }


    /**
     * @param pid      父分类编号
     * @param catLevel 获取的菜单级别
     * @return List<SpCategoryDto> 树形列表
     * @author Zhiwei Wang
     * @date 2020/3/31 9:02
     */
    private List<SpCategoryDto> findChildren(String pid, Integer catLevel) {
        List<SpCategoryDto> spoList = categoryService.getByCatPid(pid);

        if (spoList.size() > 0) {
            for (SpCategoryDto spol : spoList) {
                if (spol.getCatLevel() < catLevel) {
                    spol.setChildren(findChildren(spol.getCatId(), catLevel));
                } else {
                    return spoList;
                }
            }
            return spoList;
        } else {
            return spoList;
        }

    }


}
